import Vue from 'vue';
import vueTheme from 'theme-vue';
import VueRouter from 'vue-router';
import frontRoute from './front/index';
import adminRoute from './admin/index';
import staticRoute from './staticRoute';
const VueRouterPush = VueRouter.prototype.push;
const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return VueRouterPush.call(this, location, onResolve, onReject)
	return VueRouterPush.call(this, location).catch(err => err)
}
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return VueRouterReplace.call(this, location, onResolve, onReject)
	return VueRouterReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter);
const router = new VueRouter({
	routes: [...staticRoute, ...adminRoute, ...frontRoute]
})
const whiteList = ['404', 'Login', 'Register'];
router.beforeEach(async (to, from, next) => {
	let Theme = new vueTheme();
	let token = Vue.prototype.$session.get('token');
	let siteInfo = Vue.prototype.$local.get('siteInfo');
	let userInfo = Vue.prototype.$local.get('userInfo');
	let isLogin = !!token && !!userInfo;
	if (to.matched.some(n => n.name === 'Front')) {
		Theme.changeTheme('#930b0b');
	} else if (to.matched.some(n => n.name === 'Admin')) {
		Theme.changeTheme('#930b0b');
	} else {
		Theme.changeTheme('#930b0b');
	}
	if (to.matched.length === 0) {
		next('/404');
		return false;
	}
	if (!!token && !!userInfo) {
		if (to.name === 'Login') {
			next(from.fullPath);
		} else {
			next();
		}
	} else if (to.matched.some(n => n.name === 'Front')) {
		next();
		return false;
	} else if (!whiteList.some(n => n === to.name)) {
		next('/login');
		return false;
	} else {
		next();
		return false;
	}
})
export default router